package aar.test.tessocr;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.adapter.OrderListAdapter;
import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.UnexporderListModel;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.view.CustomLoadingMoreFooter;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.callback.StringCallback;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;
import static aar.test.tessocr.MainActivity.APP_KEY;

/**
 * author: sunshine
 * created on: 2021/1/13 17:17
 * description:
 */
public class TimeOutListForCabinetActivity extends BaseActivity implements XRecyclerView.LoadingListener{
    @BindView(R.id.rvData)
    XRecyclerView rvData;
    @BindView(R.id.ll_empty)
    LinearLayout imgEmpty;
    @BindView(R.id.title)
    TextView tvTitle;

    private List<UnexporderListModel> mList = new ArrayList<>();
    private OrderListAdapter mAdapter;
    private boolean isFirst = true;
    private int pageNum = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_today_list);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        tvTitle.setText("逾期件");

        refreshData();
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        getData();
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    private void refreshData() {
        //pageNum = 1;
        getData();
    }

    private void getData() {
        mList = (ArrayList<UnexporderListModel>) getIntent().getSerializableExtra("unexporderListModel");
        if (null != mList && mList.size() > 0) {
            LinearLayoutManager manager = new LinearLayoutManager(this);
            rvData.setLayoutManager(manager);
            mAdapter = new OrderListAdapter(this, mList);
            rvData.setAdapter(mAdapter);
            final CustomLoadingMoreFooter footer = new CustomLoadingMoreFooter(this);
            rvData.setFootView(footer, new CustomFooterViewCallBack() {
                @Override
                public void onLoadingMore(View yourFooterView) {
                    footer.onLoadingMore();
                }

                @Override
                public void onLoadMoreComplete(View yourFooterView) {
                    footer.onLoadMoreComplete();
                }

                @Override
                public void onSetNoMore(View yourFooterView, boolean noMore) {
                    footer.onSetNoMore();
                }
            });
            rvData.setPullRefreshEnabled(false);
            rvData.setLoadingMoreEnabled(false);
            rvData.setLoadingListener(TimeOutListForCabinetActivity.this);

            mAdapter.setViewClickListener(new OrderListAdapter.ViewClickListener() {
                @Override
                public void post_again(int pos) {
                    postAgain(pos);
                }

                @Override
                public void gridTackBack(int pos) {
                    expordergridGiveBack(pos);
                    expordergridOpen(pos);
                }

                @Override
                public void modify_phone(int pos) {

                }
            });
        }
    }

    @OnClick({R.id.left_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_layout:
                finish();
                break;
        }
    }

    private void postAgain(int pos) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", mList.get(pos).getId());


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_REDELIVER)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(TimeOutListForCabinetActivity.this,msg,Toast.LENGTH_SHORT).show();
                                }else if (TextUtils.equals(code, "100")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(TimeOutListForCabinetActivity.this,msg,Toast.LENGTH_SHORT).show();
                                    pageNum = 1;
                                    reGetData();
                                }
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void expordergridGiveBack(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("orderid", mList.get(pos).getId());


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_GIVE_BACK)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(TimeOutListForCabinetActivity.this,msg,Toast.LENGTH_SHORT).show();
                                }else if (TextUtils.equals(code, "100")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(TimeOutListForCabinetActivity.this,msg,Toast.LENGTH_SHORT).show();
                                    pageNum = 1;
                                    reGetData();
                                }
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });


    }

    private void reGetData() {
        final Map<String, Object> map = new HashMap<>();
        map.put("adminid", PrefUtils.getString(this, "userId", ""));
        map.put("keyword", "");
        map.put("page", "1");
        map.put("size", ConstantPara.PAGESIZE_MAX);
        map.put("cabinetId", PrefUtils.getString(this, "cabinetId", ""));


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<UnexporderListModel>>>post(Urls.URL_TIMEOUT_LIST)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<UnexporderListModel>>>(TimeOutListForCabinetActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<UnexporderListModel>>> response) {
                        mList.clear();
                        mList.addAll(response.body().data);
                        if (mList.size() == 0) {
                            finish();
                        } else {
                            mList.clear();
                            mList.addAll(response.body().data);
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<List<UnexporderListModel>>> response) {
                        finish();
                    }
                });
    }

    private void expordergridOpen(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("cabinetId", mList.get(pos).getCabinetid());
        map.put("type", "0");
        map.put("cabinetGridId", mList.get(pos).getCabinetgridid());
        map.put("adminid", PrefUtils.getString(TimeOutListForCabinetActivity.this, "userId", ""));

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_EXPUSEROPEN)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                             @Override
                             public void onSuccess(Response<String> response) {

                             }

                             @Override
                             public void onError(Response<String> response) {
                                 Log.e("MainActivity", "onError---------------------");

                             }
                         }

                );


    }
}
